﻿using CoreModule;
using HandyControl.Controls;
using Microsoft.EntityFrameworkCore;
using NPOI.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using ToastNotifications;
using ToastNotifications.Lifetime;
using ToastNotifications.Messages;
using ToastNotifications.Position;
namespace Yuwell.AtomizerWeight.App.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : System.Windows.Window, INotifier
    {

        public static int DataCountPerPage = int.MaxValue;


        Notifier notifier = new Notifier(cfg =>
        {
            cfg.DisplayOptions.Width = 600;
            cfg.PositionProvider = new WindowPositionProvider(
                parentWindow: Application.Current.MainWindow,
                corner: ToastNotifications.Position.Corner.BottomCenter,

                offsetX: 0,
                offsetY: 30);
            cfg.LifetimeSupervisor = new TimeAndCountBasedLifetimeSupervisor(
                notificationLifetime: TimeSpan.FromSeconds(3),
                maximumNotificationCount: MaximumNotificationCount.FromCount(1));
            cfg.Dispatcher = Application.Current.Dispatcher;
        });


        public MainWindow()
        {
            InitializeComponent();

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNormal_Click(object sender, RoutedEventArgs e)
        {

            if (this.WindowState == WindowState.Normal)
            {
                this.topRegion.Visibility = Visibility.Visible;
                this.WindowState = WindowState.Maximized;
                imgNormal.Source = new BitmapImage(new Uri("pack://application:,,,/Images/to-normal.png"));
            }
            else
            {

                this.WindowState = WindowState.Normal;
                imgNormal.Source = new BitmapImage(new Uri("pack://application:,,,/Images/to-max.png"));
            }

        }
        private void btnToFull_Click(object sender, RoutedEventArgs e)
        {

            this.topRegion.Visibility = Visibility.Collapsed;
            this.WindowState = WindowState.Maximized;

            this.ShowWarning("按 Esc 即可退出全屏模式");

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMinimize_Click(object sender, RoutedEventArgs e)
        {

            this.WindowState = WindowState.Minimized;
        }
        /// <summary>
        /// 
        /// </summary>
        public StringBuilder ScanCache { get; set; } = new StringBuilder();
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {

            if (e.Key == System.Windows.Input.Key.Escape
                && this.topRegion.Visibility == Visibility.Collapsed)
            {
                this.topRegion.Visibility = Visibility.Visible;
            }

            var enterKey = (char)KeyInterop.VirtualKeyFromKey(Key.Enter);
            var returnKey = (char)KeyInterop.VirtualKeyFromKey(Key.Return);
            var cancelKey = (char)KeyInterop.VirtualKeyFromKey(Key.Cancel);
            var capitalKey = (char)KeyInterop.VirtualKeyFromKey(Key.Capital);
            var capsLockKey = (char)KeyInterop.VirtualKeyFromKey(Key.CapsLock);
            char inputChar = (char)KeyInterop.VirtualKeyFromKey(e.Key); // 将按键转换为字符
            if (inputChar != enterKey
                && inputChar != returnKey
                && inputChar != cancelKey
                && inputChar != capitalKey
                && inputChar != capsLockKey)
            {
                ScanCache.Append(inputChar);
            }
            if (e.Key == Key.Enter && ScanCache.Length > 0)
            {
                string input = ScanCache.ToString().Trim();
                var parts = input
                    .Split(new char[] { enterKey, returnKey, cancelKey, capitalKey, capsLockKey }, StringSplitOptions.RemoveEmptyEntries)
                    .Distinct();
                ScanCache.Clear();
                foreach (var part in parts)
                {
                    e.Handled = true;

                    ProcessDeviceSn(part);

                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="deviceSn"></param>
        /// <param name="measureTime"></param>

        public void UpdateMeasurementResultInfoRefTime(string deviceSn, DateTime measureTime)
        {
            try
            {

                CoreModule.Storages.MySqlDbStorage storage = new CoreModule.Storages.MySqlDbStorage();

                var list = storage.MeasurementResultInfos
                    .Where(item => item.DeviceSN == deviceSn)
                    .ToList();

                foreach (var item in list)
                {
                    item.RefTime=measureTime;
                }

                storage.SaveChanges();
            } catch (Exception ex)
            {

            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="deviceSn"></param>
        /// <param name="measureWeight"></param>
        public MeasurementResultInfo Create(string deviceSn, DateTime measureTime, float measureWeight)
        {
            try
            {


                CoreModule.Storages.MySqlDbStorage storage = new CoreModule.Storages.MySqlDbStorage();
                var measurementArg = storage.MeasurementArgs
                    .Where(item => item.ClientId == CoreModule.Extension.GetClientId())
                    .OrderByDescending(item => item.RefTime)
                    .First();
                var newItem = new CoreModule.MeasurementResultInfo();
                newItem.RefTime = measureTime;
                newItem.StartTime = measureTime;
                newItem.DeviceSN = deviceSn;
                newItem.StartClientId = CoreModule.Extension.GetClientId();
                newItem.StartWeight = measureWeight;
                newItem.VaporInterval = measurementArg.VaporInterval.ToString();
                newItem.MeasurementArg = measurementArg;
                storage.MeasurementResultInfos.Add(newItem);
                storage.SaveChanges();

                return newItem;
              

            }
            catch (Exception ex)
            {
                ShowWarning(ex.Message);
            }
            return null;
        }

        /// <summary>
        /// 
        /// </summary>
       


        /// <summary>
        /// 
        /// </summary>
        /// <param name="measurementResultInfo"></param>
        private void UpdateMeasurementResultInfo(MeasurementResultInfo measurementResultInfo, DateTime endTime)
        {


            CoreModule.Storages.MySqlDbStorage storage = new CoreModule.Storages.MySqlDbStorage();
            var measurementArg = measurementResultInfo.MeasurementArg;

            measurementResultInfo.EndWeight = LastMeasureWeight;

            measurementResultInfo.EndTime = endTime;

            measurementResultInfo.RefTime = endTime;

            measurementResultInfo.EndClientId = CoreModule.Extension.GetClientId();

            var vapor = ((measurementResultInfo.StartWeight - measurementResultInfo.EndWeight.Value) / measurementArg.VaporInterval);

            measurementResultInfo.Vapor = vapor.ToString("F3");

            measurementResultInfo.VaporResult = string.Empty;


            if (vapor >= measurementArg.VaporLowValue && vapor <= measurementArg.VaporHighValue)
            {
                measurementResultInfo.VaporResult = VaporResult.合格.ToString();
            }
            else if (vapor < measurementArg.VaporLowValue)
            {
                measurementResultInfo.VaporResult = VaporResult.不合格.ToString(); ;
            }
            else if (vapor > measurementArg.VaporHighValue)
            {
                measurementResultInfo.VaporResult = VaporResult.偏大.ToString(); ;
            }
            storage.Attach(measurementResultInfo).State = EntityState.Modified;
            storage.SaveChanges();

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="deviceSn"></param>
        public void ProcessDeviceSn(string deviceSn)
        {
            deviceSn = Regex.Replace(deviceSn, @"[^a-zA-Z0-9]", "");

            if(string.IsNullOrWhiteSpace(deviceSn))
            {
                return;
            }
            if (this.LastMeasureWeight <= 0)
            {
                ShowWarning("电子秤未连接，或电子秤数据为0。");
                return;
            }

            var now = CoreModule.Storages.MySqlDbStorage.GetServerTime();
          
            try
            {
               
                var localConfigurationInfo = CoreModule.LocalConfigurationInfo.Load();

                ///
                if (localConfigurationInfo.WorkMode == WorkMode.步骤一.ToString())
                {
                    CoreModule.Storages.MySqlDbStorage storage = new CoreModule.Storages.MySqlDbStorage();
                    var measurementResultInfos = storage.MeasurementResultInfos
                                 .Include(x => x.MeasurementArg)
                                 .Where(item => item.DeviceSN == deviceSn)
                                 .ToList();

                    if (measurementResultInfos.Count == 0)
                    {
                        this.ClearScanInformation();
                        var newMeasurementResultInfo = this.Create(deviceSn, now, LastMeasureWeight);
                        this.UpdateScanInformation(newMeasurementResultInfo);
                        this.RefreshMeasurementResultInfos();
                        return;
                    }
                    ///
                    if(measurementResultInfos.Any(item=>!item.EndTime.HasValue))
                    {
                        this.ShowWarning(string.Format("此条码[{0}]未结束!",deviceSn));
                        this.RefreshMeasurementResultInfos();
                        return;
                    }
                    else
                    {
                        this.ClearScanInformation();
                        var newMeasurementResultInfo = this.Create(deviceSn, now, LastMeasureWeight);
                        this.UpdateScanInformation(newMeasurementResultInfo);
                        UpdateMeasurementResultInfoRefTime(deviceSn, now);
                        this.RefreshMeasurementResultInfos();
                        return;
                    }
                }
                else if (localConfigurationInfo.WorkMode == WorkMode.步骤二.ToString())
                {
                    CoreModule.Storages.MySqlDbStorage storage = new CoreModule.Storages.MySqlDbStorage();
                    var measurementResultInfos = storage
                          .MeasurementResultInfos
                          .Include(x => x.MeasurementArg)
                          .Where(item => item.DeviceSN == deviceSn)
                          .ToList();
                    if (measurementResultInfos.Count == 0)
                    {
                        ShowWarning("数据未找到。");
                        this.RefreshMeasurementResultInfos();
                        return;
                    }
                    ///
                    if (measurementResultInfos.All(item=>item.EndTime.HasValue))
                    {
                        ShowWarning("数据已更新，不需要扫描");
                        this.RefreshMeasurementResultInfos();
                        return;
                    }

                    foreach (var measurementResultInfo in measurementResultInfos
                        .Where(item=>!item.EndTime.HasValue)
                        .ToList())
                    {
                        var measurementArg = measurementResultInfo.MeasurementArg;
                        if ((now - measurementResultInfo.StartTime).TotalMinutes < measurementArg.VaporInterval)
                        {
                            this.ShowWarning("时间间隔太短!");
                            this.RefreshMeasurementResultInfos();
                        }
                        else
                        {
                            ClearScanInformation();
                            UpdateMeasurementResultInfo(measurementResultInfo, now);
                            UpdateScanInformation(measurementResultInfo);
                            UpdateMeasurementResultInfoRefTime(deviceSn, now);
                            this.RefreshMeasurementResultInfos();
                      }
                    }
                }
                else if (localConfigurationInfo.WorkMode == WorkMode.步骤一和步骤二.ToString())
                {

                    CoreModule.Storages.MySqlDbStorage storage = new CoreModule.Storages.MySqlDbStorage();

                    var measurementResultInfos = storage.MeasurementResultInfos
                               .Include(x => x.MeasurementArg)
                               .Where(item => item.DeviceSN == deviceSn)
                               .ToList();

                    ///
                    if (measurementResultInfos.Count==0)
                    {
                        this.ClearScanInformation();
                        var newMeasurementResultInfo = this.Create(deviceSn, now, LastMeasureWeight);
                        this.UpdateScanInformation(newMeasurementResultInfo);
                        this.RefreshMeasurementResultInfos();
                        return;
                    }
                    ///
                    if (measurementResultInfos.All(item=>item.EndTime.HasValue))
                    {
                        this.ClearScanInformation();
                        var newMeasurementResultInfo = this.Create(deviceSn, now, LastMeasureWeight);
                        this.UpdateScanInformation(newMeasurementResultInfo);
                        this.UpdateMeasurementResultInfoRefTime(deviceSn, now);
                        this.RefreshMeasurementResultInfos();
                        return;
                    }

                    foreach (var measurementResultInfo in measurementResultInfos
                       .Where(item => !item.EndTime.HasValue)
                       .ToList())
                    {
                        var measurementArg = measurementResultInfo.MeasurementArg;
                        if ((now - measurementResultInfo.StartTime).TotalMinutes < measurementArg.VaporInterval)
                        {
                            this.ShowWarning("时间间隔太短!");
                            this.RefreshMeasurementResultInfos();
                        }
                        else
                        {
                            ClearScanInformation();
                            UpdateMeasurementResultInfo(measurementResultInfo, now);
                            UpdateScanInformation(measurementResultInfo);
                            UpdateMeasurementResultInfoRefTime(deviceSn, now);
                            this.RefreshMeasurementResultInfos();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="count"></param>
        private void UpdateMaxPageCount(int count)
        {

            if (count == 0)
            {
                this.pgtList.MaxPageCount = 0;
                this.lvMeasurementResultInfos
             .ItemsSource = new List<MeasurementResultInfo>();
            }
            else
            {
                var add = count % DataCountPerPage == 0 ? 0 : 1;

                this.pgtList.MaxPageCount = count / DataCountPerPage + add;
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        public void RefreshMeasurementResultInfos(int pageIndex = 0)
        {
            try
            {
                if (pageIndex == 0)
                {
                    this.pgtList.PageIndex = 1;
                }
                var now = DateTime.Now;

                var baseTime = new DateTime(now.Year, now.Month, now.Day, 0, 0, 0);
                CoreModule.Storages.MySqlDbStorage storage = new CoreModule.Storages.MySqlDbStorage();
                var count = storage
                    .MeasurementResultInfos
                    .Count(item => item.RefTime > baseTime);

                this.txtEntityTotalCount.Text = count.ToString();


                this.UpdateMaxPageCount(count);


                var data = storage.MeasurementResultInfos
                                .Where(item => item.RefTime > baseTime)
                                .OrderByDescending(item => item.RefTime)
                                .ThenByDescending(item => item.StartTime)
                                .Skip(pageIndex * DataCountPerPage)
                                .Take(DataCountPerPage)
                                .ToList();

                this.lvMeasurementResultInfos
                    .ItemsSource = data;

                this.lvMeasurementResultInfos.UpdateLayout();
              
                


            }
            catch (Exception ex)
            {
                ShowWarning(ex.Message);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void topRegion_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            e.Handled = true;
        }
        private void topRegion_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            e.Handled = true;
        }
        private void topRegion_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            e.Handled = true;
        }
        private void topRegion_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            e.Handled = true;
        }
        public bool IsShowConfigurationHome = false;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnActivated(EventArgs e)
        {
            base.OnActivated(e);
        }

        Style DefaultPaginationButtonStyle { get; set; } = default(Style);



        /// <summary>
        /// 
        /// </summary>
        /// <param name="arg"></param>
        private void UpdateArgLable(MeasurementArg arg)
        {
            this.txtArgVaporInterval.Text = string.Format("{0}分钟", arg.VaporInterval.ToString());
            this.txtVaporValueRange.Text = string.Format("{0}到{1} ML/Min", arg.VaporLowValue.ToString("F2")
                , arg.VaporHighValue.ToString("F2"));
        }

        /// <summary>
        /// 
        /// </summary>

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            pgtList.Visibility = Visibility.Hidden;


             LoginWindow loginWindow = new LoginWindow();
            loginWindow.Owner = this;

            if (loginWindow.ShowDialog() == false)
            {
                Application.Current.Shutdown();
                return;
            }
            this.txtPortName.Text = "--";
            this.txtWorkMode.Text = "--";


            //LocalizeDictionary.Instance.SetCurrentThreadCulture = true;
            //LocalizeDictionary.Instance.Culture = new CultureInfo("zh");




            ///
            DefaultPaginationButtonStyle = this.FindResource("DefaultPaginationButtonStyle") as Style;

            UpdatePaginationStyle(this.pgtList);

            this.RefreshMeasurementResultInfos();

            var info = LocalConfigurationInfo.Load();

            if (info.WorkMode == WorkMode.步骤二.ToString())
            {
                this.txtArgVaporInterval.Text = "--";
                this.txtVaporValueRange.Text = "--";
            }
            else
            {
                CoreModule.Storages.MySqlDbStorage storage = new CoreModule.Storages.MySqlDbStorage();
                var arg = storage.MeasurementArgs
                    .Where(item => item.ClientId == CoreModule.Extension.GetClientId())
                    .OrderByDescending(item => item.RefTime)
                    .First();
                this.UpdateArgLable(arg);
            }


            if (!string.IsNullOrWhiteSpace(info.PortName))
            {
                this.StartMeasurementDevice(info.PortName);
            }

            this.txtPortName.Text = info.PortName;
            this.txtWorkMode.Text = info.WorkMode;


            this.ClearScanInformation();

            this.txtVaporResult.Text = string.Empty;



        }


        /// <summary>
        /// 
        /// </summary>
        private SerialPort MeasurementDevice { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="portName"></param>
        private void StartMeasurementDevice(string portName)
        {
            if (MeasurementDevice != null)
            {
                MeasurementDevice.Dispose();
                MeasurementDevice = null;
            }
             

            MeasurementDevice = new SerialPort();

            try
            {
                MeasurementDevice.PortName = portName;
                MeasurementDevice.BaudRate = 9600;
                MeasurementDevice.DataBits = 8;
                MeasurementDevice.StopBits = StopBits.One;
                MeasurementDevice.Parity = Parity.None;
                MeasurementDevice.Encoding = Encoding.ASCII;

                //准备就绪              
                MeasurementDevice.DtrEnable = true;
                MeasurementDevice.RtsEnable = true;
                //设置数据读取超时为1秒
                MeasurementDevice.ReadTimeout = 1000;

                MeasurementDevice.DataReceived += MeasurementDevice_DataReceived;
                MeasurementDevice.ErrorReceived += MeasurementDevice_ErrorReceived;
                MeasurementDevice.Open();
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 
        /// </summary>
        public float LastMeasureWeight { get; set; } = 0;

        /// <summary>
        /// 
        /// </summary>
        public string DeviceCache { get; set; } = string.Empty;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MeasurementDevice_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
        {

            LastMeasureWeight = 0;
             
            //this.ShowWarning("称重设备离线!");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void MeasurementDevice_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            try
            {
                var value = this.MeasurementDevice.ReadExisting();

                this.DeviceCache += value;

                if (this.DeviceCache.Contains('\n'))
                {

                    List<string> inputs = this.DeviceCache.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                        .ToList();
                    DeviceCache = string.Empty;
                    foreach (var item in inputs)
                    {
                        ProcessMeasurementResult(item);
                    }
                }

            }
            catch (Exception ex)
            {

            }
        }
        /// <summary>
        /// 
        /// </summary>

        public int UpdateIndex = 0;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="measurementResult"></param>
        public void ProcessMeasurementResult(string measurementResult)
        {
            var numberStr = Regex.Replace(measurementResult, @"[^.0-9]", "");
            if (float.TryParse(numberStr, out var value))
            {
                LastMeasureWeight = value;
            }       
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pagination"></param>
        private void UpdatePaginationStyle(Pagination pagination)
        {
            var panelMain = (StackPanel)pagination.Template.FindName("PART_PanelMain", pagination);

            foreach (RadioButton item in panelMain.Children)
            {
                item.Style = DefaultPaginationButtonStyle;
            }
        }

        public void ShowInformation(string message)
        {
            notifier.ClearMessages(new DefaultClearStrategy());

            notifier.ShowInformation(message, new ToastNotifications.Core.MessageOptions() { ShowCloseButton = false });
        }
        public void ShowSuccess(string message)
        {
            notifier.ClearMessages(new DefaultClearStrategy());
            notifier.ShowSuccess(message, new ToastNotifications.Core.MessageOptions() { ShowCloseButton = false });
        }
        public void ShowWarning(string message)
        {
            notifier.ClearMessages(new DefaultClearStrategy());
            notifier.ShowWarning(message, new ToastNotifications.Core.MessageOptions() { ShowCloseButton = false });
        }
        public void ShowError(string message)
        {
            notifier.ClearMessages(new DefaultClearStrategy());
            notifier.ShowError(message, new ToastNotifications.Core.MessageOptions() { ShowCloseButton = false });
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Unloaded(object sender, RoutedEventArgs e)
        {

            notifier.Dispose();

            if (this.MeasurementDevice != null)
            {
                this.MeasurementDevice.Dispose();
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnManual_Click(object sender, RoutedEventArgs e)
        {

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnShowDocument_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Window_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {

        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            e.Cancel = true;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closed(object sender, EventArgs e)
        {
            if (this.MeasurementDevice != null)
            { this.MeasurementDevice.Close(); }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pgtList_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {

            var pageIndex = e.Info - 1;

            this.RefreshMeasurementResultInfos(pageIndex);
            UpdatePaginationStyle(sender as Pagination);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSecondary_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            var btn = sender as System.Windows.Controls.Button;
            btn.Background = new SolidColorBrush(Color.FromRgb(0xF1, 0xF0, 0xF5));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnSecondary_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            var btn = sender as System.Windows.Controls.Button;
            btn.Background = new SolidColorBrush(Colors.Transparent);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnVaporArgs_Click(object sender, RoutedEventArgs e)
        {
            CoreModule.Storages.MySqlDbStorage storage = new CoreModule.Storages.MySqlDbStorage();
            mask.Visibility = Visibility.Visible;
            VaporArgsWindow window = new VaporArgsWindow();
            window.Owner = this;
            window.ShowDialog();

            mask.Visibility = Visibility.Hidden; ;

            ClearScanInformation();

            var arg = storage.MeasurementArgs
                .Where(item => item.ClientId == CoreModule.Extension.GetClientId())
              .OrderByDescending(item => item.RefTime)
              .FirstOrDefault();
            if (arg != null)
            {
                UpdateArgLable(arg);
            }
            ClearScanInformation();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, RoutedEventArgs e)
        {


            mask.Visibility = Visibility.Visible;
            CloseWindow closeWindow = new CloseWindow();
            closeWindow.Owner = this;
            if (closeWindow.ShowDialog() == true)
            {
                Application.Current.Shutdown();
                return;
            }
            mask.Visibility = Visibility.Hidden; ;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPortName_Click(object sender, RoutedEventArgs e)
        {
            mask.Visibility = Visibility.Visible;

            SeriesPortWindow window = new SeriesPortWindow();
            window.Owner = this;
            if (window.ShowDialog() == true)
            {
                var info = LocalConfigurationInfo.Load();
                if (string.IsNullOrEmpty(info.PortName))
                {
                    return;
                }
                var portNames = SerialPort.GetPortNames().ToList();

                if (!portNames.Contains(info.PortName))
                {
                    return;
                }
                this.StartMeasurementDevice(info.PortName);
                this.txtPortName.Text = info.PortName;
            }
            mask.Visibility = Visibility.Hidden;

            var newInfo = LocalConfigurationInfo.Load();
            this.txtPortName.Text = newInfo.PortName;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnHistory_Click(object sender, RoutedEventArgs e)
        {
            mask.Visibility = Visibility.Visible;
            HistoryWindow window = new HistoryWindow();
            window.Owner = this;
            if (window.ShowDialog() == true)
            {
                Application.Current.Shutdown();
                return;
            }
            mask.Visibility = Visibility.Hidden;
            this.RefreshMeasurementResultInfos();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRefresh_Click(object sender, RoutedEventArgs e)
        {
            this.RefreshMeasurementResultInfos();
            this.ShowSuccess("手动刷新数据完成。");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnDb_Click(object sender, RoutedEventArgs e)
        {
            mask.Visibility = Visibility.Visible;
            DbWindow window = new DbWindow();
            window.Owner = this;
            window.ShowDialog();
            mask.Visibility = Visibility.Hidden;
        }

        /// <summary>
        /// 
        /// </summary>
        public void UpdateFinalMeasurementResultInfoToUI(MeasurementResultInfo measurementResultInfo)
        {


        }

        /// <summary>
        /// 
        /// </summary>
        public void ClearScanInformation()
        {
            this.txtDeviceSN.Text = "--";
            this.txtStartTime.Text = "--";
            this.txtStartWeight.Text = "--";

            this.txtVapor.Text = "--";
            this.txtEndTime.Text = "--";
            this.txtEndWeight.Text = "--";

            this.txtVaporResult.Text = "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="measurementResultInfo"></param>
        public void UpdateScanInformation(MeasurementResultInfo measurementResultInfo)
        {

            if (measurementResultInfo == null)
            { return; }
            if (measurementResultInfo.EndTime.HasValue)
            {
                this.txtDeviceSN.Text = measurementResultInfo.DeviceSN;
                this.txtStartTime.Text = measurementResultInfo.StartTime.ToString();
                this.txtStartWeight.Text = measurementResultInfo.StartWeight.ToString();

                this.txtVapor.Text = measurementResultInfo.Vapor.ToString();
                this.txtEndTime.Text = measurementResultInfo.EndTime.ToString();
                this.txtEndWeight.Text = measurementResultInfo.EndWeight?.ToString("F3");
                this.txtVaporResult.Text = measurementResultInfo.VaporResult.ToString();

                if (measurementResultInfo.VaporResult == CoreModule.VaporResult.合格.ToString())
                {
                    this.txtVaporResult.Foreground = new SolidColorBrush(Colors.Green);
                }
                else if (measurementResultInfo.VaporResult == CoreModule.VaporResult.不合格.ToString())
                {
                    this.txtVaporResult.Foreground = new SolidColorBrush(Colors.Red);
                }
                else
                {
                    this.txtVaporResult.Foreground = new SolidColorBrush(Colors.Purple);
                }
            }
            else
            {
                this.txtDeviceSN.Text = measurementResultInfo.DeviceSN;
                this.txtStartTime.Text = measurementResultInfo.StartTime.ToString();
                this.txtStartWeight.Text = measurementResultInfo.StartWeight.ToString();

                this.txtVapor.Text = "--";
                this.txtEndTime.Text = "--";
                this.txtEndWeight.Text = "--";
                this.txtVaporResult.Text = string.Empty;

            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnWorkMode_Click(object sender, RoutedEventArgs e)
        {
            mask.Visibility = Visibility.Visible;
            WorkModeWindow window = new WorkModeWindow();
            window.Owner = this;
            window.ShowDialog();
            mask.Visibility = Visibility.Hidden;

            var info = LocalConfigurationInfo.Load();

            var workMode = info.WorkMode;
            this.txtWorkMode.Text = info.WorkMode;

            ClearScanInformation();


            if (info.WorkMode == WorkMode.步骤二.ToString())
            {
                this.txtArgVaporInterval.Text = "--";
                this.txtVaporValueRange.Text = "--";
            }
            else
            {
                CoreModule.Storages.MySqlDbStorage storage = new CoreModule.Storages.MySqlDbStorage();
                var arg = storage.MeasurementArgs
                    .Where(item => item.ClientId == CoreModule.Extension.GetClientId())
                    .OrderByDescending(item => item.RefTime)
                    .First();
                this.UpdateArgLable(arg);
            }



        }
    }

}
